<template>
  <div class="allocation-container">
    <h2 class="title">宿舍分配管理</h2>

    <!-- 独立搜索区域 -->
    <div class="search-area">
      <h3>学生信息搜索</h3>
      <el-input v-model="searchQuery" placeholder="请输入姓名或学号进行搜索" class="search-input" />
      <el-button type="primary" @click="performSearch">搜索</el-button>
    </div>

    <!-- 搜索结果表格 -->
    <el-table :data="searchResults" border stripe style="width: 100%; margin-bottom: 40px;" v-if="searchResults.length > 0">
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="studentId" label="学号"></el-table-column>
      <el-table-column prop="class" label="班级"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="selectStudent(scope.row)">选择该学生</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分配表单 -->
    <el-form :model="form" label-width="120px" class="allocation-form">
      <el-form-item label="选择学生">
        <el-select v-model="form.studentId" placeholder="请选择学生" style="width: 100%" filterable>
          <el-option
            v-for="student in unallocatedStudents"
            :key="student.id"
            :label="`${student.name} - ${student.studentId}`"
            :value="student.id">
            <span>{{ student.name }}</span>
            <span style="color: #999; margin-left: 10px;">{{ student.studentId }} ({{ student.class }})</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="选择宿舍">
        <el-select v-model="form.dormitoryId" placeholder="请选择宿舍" style="width: 100%">
          <el-option
            v-for="dormitory in availableDormitories"
            :key="dormitory.id"
            :label="`宿舍 ${dormitory.roomNumber}（剩余床位：${dormitory.availableBeds}）`"
            :value="dormitory.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitAllocation">提交分配</el-button>
      </el-form-item>
    </el-form>

    <!-- 已分配列表 -->
    <el-table :data="allocatedList" border stripe style="width: 100%; margin-top: 30px;">
      <el-table-column prop="studentName" label="学生姓名"></el-table-column>
      <el-table-column prop="studentId" label="学号"></el-table-column>
      <el-table-column prop="roomNumber" label="宿舍号"></el-table-column>
      <el-table-column prop="bedCount" label="总床位数"></el-table-column>
      <el-table-column prop="availableBeds" label="剩余床位"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="removeAllocation(scope.row)">取消分配</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      searchResults: [],
      form: {
        studentId: null,
        dormitoryId: null
      },
      allocations: [] // 存储已分配关系
    }
  },
  computed: {
    students() {
      return this.$store.getters.students
    },
    dormitories() {
      return this.$store.getters.dormitories
    },
    unallocatedStudents() {
      const allocatedStudentIds = this.allocations.map(a => a.studentId)
      return this.students.filter(s => !allocatedStudentIds.includes(s.id))
    },
    availableDormitories() {
      return this.dormitories.filter(d => d.availableBeds > 0)
    },
    allocatedList() {
      return this.allocations.map(allocation => {
        const student = this.students.find(s => s.id === allocation.studentId)
        const dormitory = this.dormitories.find(d => d.id === allocation.dormitoryId)
        return {
          studentName: student ? student.name : '未知',
          studentId: student ? student.studentId : '未知',
          roomNumber: dormitory ? dormitory.roomNumber : '未知',
          bedCount: dormitory ? dormitory.bedCount : 0,
          availableBeds: dormitory ? dormitory.availableBeds : 0,
          studentId: allocation.studentId,
          dormitoryId: allocation.dormitoryId
        }
      })
    }
  },
  methods: {
    performSearch() {
      const query = this.searchQuery.trim().toLowerCase()
      if (!query) {
        this.searchResults = []
        return
      }

      this.searchResults = this.students.filter(student =>
        student.name.toLowerCase().includes(query) ||
        student.studentId.includes(query)
      )
    },
    selectStudent(student) {
      if (this.unallocatedStudents.some(s => s.id === student.id)) {
        this.form.studentId = student.id
        this.$message.success(`已选择：${student.name}`)
      } else {
        this.$message.warning('该学生已分配宿舍')
      }
    },
    submitAllocation() {
      if (!this.form.studentId || !this.form.dormitoryId) {
        this.$message.warning('请选择学生和宿舍')
        return
      }

      const dormitory = this.dormitories.find(d => d.id === this.form.dormitoryId)

      if (dormitory && dormitory.availableBeds <= 0) {
        this.$message.error('该宿舍已满，请选择其他宿舍')
        return
      }

      // 添加分配记录111
      this.allocations.push({ ...this.form })

      // 更新宿舍剩余床位
      this.$store.dispatch('updateDormitory', {
        ...dormitory,
        availableBeds: dormitory.availableBeds - 1
      })

      this.$message.success('分配成功')

      // 重置表单
      this.form.studentId = null
      this.form.dormitoryId = null
    },
    removeAllocation(row) {
      // 删除分配记录
      this.allocations = this.allocations.filter(
        a => !(a.studentId === row.studentId && a.dormitoryId === row.dormitoryId)
      )

      // 增加对应宿舍的可用床位
      const dormitory = this.dormitories.find(d => d.id === row.dormitoryId)
      if (dormitory) {
        this.$store.dispatch('updateDormitory', {
          ...dormitory,
          availableBeds: dormitory.availableBeds + 1
        })
      }

      this.$message.success('取消分配成功')
    }
  }
}
</script>

<style scoped>
.allocation-container {
  padding: 20px;
  background-color: #f9f9f9;
}

.title {
  color: #333;
  font-size: 24px;
  margin-bottom: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
  margin-right: 10px;
}

.allocation-form {
  max-width: 600px;
}
</style>